package me.numark.activities;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.squareup.picasso.Picasso;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.AskLoginFragment;
import me.numark.fragments.HotFragment;
import me.numark.model.BaseListResponse;
import me.numark.model.Feed;
import me.numark.model.News;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.ShareContentWebpage;
import me.numark.utils.SinaShareManager;
import me.numark.utils.Utils;
import me.numark.view.PopupMoreView;
import me.numark.view.TencentWebViewClient;

/**
 * Created by tian on 14/11/16:下午10:41.
 */
public class ArticleActivity extends BaseActivity implements View.OnClickListener, IUiListener {

    @Bind(R.id.web_root)
    LinearLayout root;

    @Bind(R.id.webview)
    WebView webview;

    @Bind(R.id.recommend)
    View recommendButton;

    @Bind(R.id.total_recommends)
    TextView totalRecommends;

    @Bind(R.id.total_share)
    TextView totalShare;

    private News mNews;
    private int feedId;

    private List<String> urlStrings=new ArrayList<>();
    String title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_article;
        super.onCreate(savedInstanceState);
        try {
            mNews = new Gson()
                    .fromJson(getIntent().getStringExtra(Constants.NEWS_EXTRA), News.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            finish();
        }

        feedId = getIntent().getIntExtra(Constants.FEED_ID,0);
        totalRecommends.setText(String.valueOf(mNews.label_num));
        totalRecommends.setOnClickListener(this);
        totalShare.setOnClickListener(this);
       //Log.d("NewsUrl", mNews.url);
        recommendButton.setOnClickListener(this);
        WebSettings webSettings = webview.getSettings();
        if (Build.VERSION.SDK_INT >= 19){
            webview.getSettings().setLoadsImagesAutomatically(true);
        } else {
            webview.getSettings().setLoadsImagesAutomatically(false);
        }


        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setAllowFileAccess(true);
        webview.setWebViewClient(new TencentWebViewClient(urlStrings));

        webview.loadUrl(mNews.url);
        if (Global.isLoggedIn())
            readNews();
    }

    public String getNewsUrl(){
        String urlString = null;
        if (feedId==0){
            urlString = String.format(NetworkConstants.SHARE_URL,mNews.id,1);
        }else {
            urlString = String.format(NetworkConstants.SHARE_URL,feedId,0);
        }
        return urlString;
    }

    void readNews() {
        new RequestServerTask<BaseListResponse>(BaseListResponse.class,
                this,
                getString(R.string.progress_comment)) {
            @Override
            protected String requestServer() {
                String url = String.format(NetworkConstants.READ_NEWS_URL, Global.getCurrentUid(), mNews.id);
                return HttpUtil.get(url, null);
            }

            @Override
            protected void onSuccess(BaseListResponse result) {
                
            }
        }.start();
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.recommend: {
                if (!Global.isLoggedIn()) {
                    AskLoginFragment.show(this);
                    return;
                }
               // Intent intent = new Intent(this, MarkActivity.class);

                Intent intent = new Intent(this,PublishActivity.class);
                if (!TextUtils.isEmpty(mNews.title)) {
                    intent.putExtra(WebviewActivity.EXTRA_TITLE, mNews.title);
                }
                intent.putExtra(Constants.EXTRA_URL,mNews.url);

                startActivity(intent);
                finish();
            }
            break;
            case R.id.total_recommends: {
                if (!Global.isLoggedIn()) {
                    AskLoginFragment.show(this);
                    return;
                }
               //TODO 跳转至详情
                Intent intent = new Intent(this,MarkDetailActivity.class);
                Feed feed = new Feed();
                feed.news = mNews;
                intent.putExtra(Constants.FEED_EXTRA,feed.toString());
                Log.d("ArticleFeed",feed.toString());
                intent.putExtra(MarkDetailActivity.EXTRA_ORIG_TYPE,Constants.FEEDTYPE_TAG_HOT);
                startActivity(intent);
            }
            break;
            case R.id.total_share:
                //TODO 分享
                showMore();
                break;

            case R.id.share_weixin:
                dismissShowMore();
                Utils.wechatShare(0, getNewsUrl(), mNews.title, title, getNewsPic());
                break;
            case R.id.share_circle:
                dismissShowMore();
                Utils.wechatShare(1, getNewsUrl(), mNews.title, title, getNewsPic());
                break;
            case R.id.share_qq: {
                dismissShowMore();
                Tencent mTencent = null;
                try {
                    mTencent = Tencent.createInstance(Constants.TencentAppId, this);
                } catch (Throwable e) {
                    e.printStackTrace();
                    return;
                }
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, mNews.title);
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY,title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, getNewsUrl());
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, getNewsPicUrl());
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "怒马");
//                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
                mTencent.shareToQQ(this, params, this);
            }
            break;
            case R.id.share_qzone: {
                dismissShowMore();
                Tencent mTencent = null;
                try {
                    mTencent = Tencent.createInstance(Constants.TencentAppId, this);
                } catch (Throwable e) {
                    e.printStackTrace();
                    return;
                }
                final Bundle params = new Bundle();
                params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
                params.putString(QzoneShare.SHARE_TO_QQ_TITLE, mNews.title);
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,  title);
                ArrayList<String> value = new ArrayList<>();
                value.add(getNewsPicUrl());
                params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, value);
                params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,getNewsUrl());
                // params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL,mFeed.news.face_img);
                params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "怒马");
//                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
                mTencent.shareToQzone(this, params, this);
            }
            break;
            case R.id.share_weibo: {
                dismissShowMore();
                SinaShareManager manager = new SinaShareManager();
                manager.registSina(this);
                ShareContentWebpage webpage
                        = new ShareContentWebpage(mNews.title,"",getNewsUrl(),getNewsPic());
                manager.shareWebPage(webpage,this);
            }
            break;
            case R.id.more_browser: {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mNews.url));
                startActivity(browserIntent);
                dismissShowMore();
            }
            break;
            case R.id.more_copy: {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(ClipData.newPlainText("url", mNews.url));
                Utils.showToast(getString(R.string.already_copy_url));
                dismissShowMore();
            }
            break;
            default:
                break;
        }
    }

    public Bitmap getNewsPic() {
        ImageView imageView = new ImageView(this);
        if (TextUtils.isEmpty(mNews.face_img)) {
            Picasso.with(this).load(R.drawable.share_default)
                    .into(imageView);
        } else {
            Picasso.with(this).load(mNews.face_img)
                    .into(imageView);
        }
        Drawable drawable = imageView.getDrawable();
        if (drawable != null){
            return Utils.drawableToBitmap(drawable);
        }
        return null;
    }

    public String getNewsPicUrl(){
        if (TextUtils.isEmpty(mNews.face_img)){
            return NetworkConstants.NEWS_DEFAULT_URL;
        }else
            return mNews.face_img;
    }

    private void callHiddenWebViewMethod(String name) {
        if (webview != null) {
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(webview);
            }
            catch (NoSuchMethodException e) {
                Log.i("No such method: " + name, e.toString());
            }
            catch (IllegalAccessException e) {
                Log.i("Illegal Access: " + name, e.toString());
            }
            catch (InvocationTargetException e) {
                Log.d("InvocationTarget" + name, e.toString());
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        webview.onPause();
        /*if (isFinishing()){
            webview.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }*/
        //callHiddenWebViewMethod("onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        webview.onResume();
        //callHiddenWebViewMethod("onResume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        root.removeView(webview);
        webview.removeAllViews();
        webview.destroy();
    }

    PopupMoreView mPopupMoreView;

    public void dismissShowMore() {
        if (mPopupMoreView != null) {
            mPopupMoreView.dismiss();
            mPopupMoreView = null;
        }
    }

    public void showMore() {
        dismissShowMore();
        mPopupMoreView = new PopupMoreView(this);
        mPopupMoreView.noDisplayButton.setVisibility(View.GONE);
        mPopupMoreView.noWatchButton.setVisibility(View.GONE);
        mPopupMoreView.moreReport.setVisibility(View.GONE);
        mPopupMoreView.moreDelete.setVisibility(View.GONE);
        mPopupMoreView.shareCircle.setOnClickListener(this);
        mPopupMoreView.shareQQ.setOnClickListener(this);
        mPopupMoreView.shareQZone.setOnClickListener(this);
        mPopupMoreView.shareWeibo.setOnClickListener(this);
        mPopupMoreView.shareWeixin.setOnClickListener(this);
        mPopupMoreView.moreCopy.setOnClickListener(this);
        mPopupMoreView.moreBrowser.setOnClickListener(this);
        mPopupMoreView.show();
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }
}
